use tauri::{
    menu::{Menu, MenuItem, PredefinedMenuItem},
    tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
    AppHandle, Manager, Runtime,
};

pub fn create_tray<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
    let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
    let show_i = MenuItem::with_id(app, "show", "Show", true, None::<&str>)?;
    let hide_i = MenuItem::with_id(app, "hide", "Hide", true, None::<&str>)?;
    let settings_i = MenuItem::with_id(app, "settings", "Settings", true, None::<&str>)?;
    let about_i = MenuItem::with_id(app, "about", "About", true, None::<&str>)?;

    let menu = Menu::with_items(
        app,
        &[
            &show_i,
            &hide_i,
            &PredefinedMenuItem::separator(app)?,
            &settings_i,
            &about_i,
            &PredefinedMenuItem::separator(app)?,
            &quit_i,
        ],
    )?;

    let _ = TrayIconBuilder::with_id("main")
        .tooltip("Tauri Modern Template")
        .icon(app.default_window_icon().unwrap().clone())
        .menu(&menu)
        .show_menu_on_left_click(false)
        .on_menu_event(move |app, event| match event.id.as_ref() {
            "quit" => {
                log::info!("Quit menu item clicked");
                app.exit(0);
            }
            "show" => {
                log::info!("Show menu item clicked");
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                }
            }
            "hide" => {
                log::info!("Hide menu item clicked");
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.hide();
                }
            }
            "settings" => {
                log::info!("Settings menu item clicked");
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                    // Navigate to settings page
                    let _ = window.eval("window.location.hash = '#/settings'");
                }
            }
            "about" => {
                log::info!("About menu item clicked");
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                    // Navigate to about page
                    let _ = window.eval("window.location.hash = '#/about'");
                }
            }
            _ => {
                log::warn!("Unknown menu item clicked: {:?}", event.id);
            }
        })
        .on_tray_icon_event(|tray, event| {
            match event {
                TrayIconEvent::Click {
                    button: MouseButton::Left,
                    button_state: MouseButtonState::Up,
                    ..
                } => {
                    log::info!("Tray icon left clicked");
                    let app = tray.app_handle();
                    if let Some(window) = app.get_webview_window("main") {
                        match window.is_visible() {
                            Ok(true) => {
                                let _ = window.hide();
                            }
                            Ok(false) => {
                                let _ = window.show();
                                let _ = window.set_focus();
                            }
                            Err(e) => {
                                log::error!("Failed to get window visibility: {}", e);
                            }
                        }
                    }
                }
                TrayIconEvent::Click {
                    button: MouseButton::Right,
                    button_state: MouseButtonState::Up,
                    ..
                } => {
                    log::info!("Tray icon right clicked");
                    // Right click shows context menu automatically
                }
                TrayIconEvent::DoubleClick {
                    button: MouseButton::Left,
                    ..
                } => {
                    log::info!("Tray icon double clicked");
                    let app = tray.app_handle();
                    if let Some(window) = app.get_webview_window("main") {
                        let _ = window.show();
                        let _ = window.set_focus();
                    }
                }
                _ => {
                    log::debug!("Other tray event: {:?}", event);
                }
            }
        })
        .build(app);

    Ok(())
}

pub fn update_tray_tooltip<R: Runtime>(app: &AppHandle<R>, tooltip: &str) -> tauri::Result<()> {
    if let Some(tray) = app.tray_by_id("main") {
        tray.set_tooltip(Some(tooltip))?;
    }
    Ok(())
}

pub fn update_tray_menu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<()> {
    if let Some(_tray) = app.tray_by_id("main") {
        // You can update the menu dynamically here
        // For example, enable/disable items based on app state
        log::info!("Tray menu updated");
    }
    Ok(())
}
